import { getDB } from "../../utils/db/mysql";

export default defineEventHandler(async (event) => {
  let { page, size, path, dateTitle, classifyname, xiaofangfourchildren } =
    await readBody(event);


  // 使用参数化查询防止 SQL 注入
  let con = getDB();
  let result;
  let total;
  //下面15个标题
  if (classifyname) {
    //表示分类的数据渲染    侧边栏的渲染
    // 改成时间 , 方便后面插入内容 能显示在第一条
    let sql = `SELECT * FROM classifylist WHERE classifyName = ? ORDER BY creatTime DESC LIMIT ?, ?`;
    let sql2 = `SELECT COUNT(*) as count FROM classifylist WHERE classifyName = ?`;
    let params = [classifyname, (page - 1) * size, size];
    [result] = await con.execute(sql, params);
    [total] = await con.execute(sql2, [classifyname]);
  } else if (dateTitle) {
    // 携带dateTitle 就 证明 查询时间的
    // 改成时间 , 方便后面插入内容 能显示在第一条
    let sql = `SELECT * FROM pigeonholelist WHERE datatime = ? ORDER BY creatTime DESC  LIMIT ?, ?`;
    let sql2 = `SELECT COUNT(*) as count FROM pigeonholelist WHERE datatime = ?`;
    let params = [dateTitle, (page - 1) * size, size];


    [result] = await con.execute(sql, params);
    [total] = await con.execute(sql2, [dateTitle]);
  } else {
    // 改成时间 , 方便后面插入内容 能显示在第一条
    let sql = `SELECT * FROM classifylist WHERE sort = ? ORDER BY creatTime DESC LIMIT ?, ?`;
    let sql2 = `SELECT COUNT(*) as count FROM classifylist WHERE sort = ?`;
    let params = [path, (page - 1) * size, size];
    let countParams = [path];
    [result] = await con.execute(sql, params);
    [total] = await con.execute(sql2, countParams);
  }

  // 准备查询参数

  // 释放数据库连接
  await con.end();

  if (result.length !== 0) {
    return {
      code: 2000,
      data: result,
      count: total,
    };
  } else {
    return {
      code: 4003,
      data: "没有数据",
    };
  }
});
